"""
Author: Mr.Sun
Datetime: 2023/5/10 15:10 
FileName: decorators.py
Desc:  装饰器方法
"""

import sys
import datetime
import traceback
from functools import wraps
from .logger import logger


def except_decorator(func):
    @wraps(func)
    def handle_except(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            exc_type, exc_instance, exc_traceback = sys.exc_info()
            formatted_traceback = ''.join(traceback.format_tb(exc_traceback))
            message = '\n{0}\n{1}:\n{2}'.format(
                formatted_traceback,
                exc_type.__name__,
                exc_instance
            )
            logger.error("function: " + str(func.__name__) + "() 的错误信息: " + str(e))
            return e
        finally:
            pass

    return handle_except


@except_decorator
def spend_time(func):
    def time_detail(*args, **kwargs):
        start_time = datetime.datetime.now()
        logger.info("程序运行开始时间 : " + str(start_time))
        result = func(*args, **kwargs)
        end_time = datetime.datetime.now()
        logger.info("程序运行结束时间 : " + str(end_time))
        time_spend = end_time - start_time
        logger.info("程序运行耗时: " + str(time_spend))
        return result

    return time_detail
